#include "resolve_result_s.h"
#include "command.h"
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>

// all_data_len是data数据的长度,data_start是data数据的起始地址
int toSend(int *all_data_len, char *data_start, const commandResult_t *result) {
  if (result == NULL || result->result_ls == NULL || result->ls_linenum <= 0)
    return -1;
  int max_len = 0;
  for (int i = 0; i < result->ls_linenum; i++) {
    int ll = strlen(result->result_ls[i]);
    max_len = ll > max_len ? ll : max_len;
  }
  if (max_len == 0)
    return 1;
  max_len++;
  *all_data_len = max_len * result->ls_linenum + 1;
  *all_data_len += sizeof(int);

  data_start = calloc(max_len * result->ls_linenum, sizeof(char));
  memcpy(data_start,all_data_len,sizeof(int));
  for (int i = 0; i < result->ls_linenum; i++) {
    strcpy(data_start + i * max_len+sizeof(int), result->result_ls[i]);
  }
  return 0;
}

// all_data_len是data数据的长度,data_start是data数据的起始地址
int toRecv(int all_data_len, char *data_start, commandResult_t *result) {
  if (data_start == NULL||all_data_len<sizeof(int)) {
    return -1;
  }
  int off_set;
  memcpy(&off_set,data_start,sizeof(int));
  int item_num=(all_data_len-sizeof(int))/off_set;
  result->result_ls=calloc(item_num,sizeof(char*));
  for (int i = 0; i < item_num; i++)
  {
    result->result_ls[0]=calloc(off_set,sizeof(char));
    memcpy(result->result_ls[0],data_start+sizeof(int)+i*off_set,off_set);
  }
  return 0;
}